<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="申请类型" prop="applyType">
        <el-select v-model="queryParams.applyType" placeholder="请选择申请类型" clearable size="small">
          <el-option
            v-for="dict in applyTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="state" class="item">
        <el-select v-model="queryParams.state" placeholder="请选择工作状态" clearable size="small">
          <el-option
            v-for="dict in stateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['workflow:apply:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['workflow:apply:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['workflow:apply:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['workflow:apply:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

    <el-table v-loading="loading" :data="applyList" @selection-change="handleSelectionChange"  border style="width: 100%" height="600">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请类型" align="center" prop="applyType" :formatter="applyTypeFormat" />
      <el-table-column label="审批内容" align="center" prop="remark" />
      <el-table-column label="完成情况" align="center" prop="completion" />
      <el-table-column label="状态" align="center" prop="state" :formatter="stateFormat" >
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope"> 
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleFileUpload(scope.row)"
          >附件</el-button>
          <el-button
            type="text"
            icon="el-icon-check"
            size="mini"
            v-show="applyList[scope.$index].state==2"
            @click="handleCheckOnePerson(scope.row)"
          >提交审核</el-button>
          <el-button
            type="text"
            icon="el-icon-notebook-1"
            size="mini"
            @click="handleLog(scope.row)"
          >查看日志</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['workflow:apply:edit']"
          >修改</el-button> -->
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['workflow:apply:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工作申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="申请类型" prop="applyType">
          <el-select v-model="form.applyType" placeholder="请选择申请类型">
            <el-option
              v-for="dict in applyTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请内容">
          <editor v-model="form.remark" :min-height="192"/>
        </el-form-item>
        <el-form-item label="申请时间" prop="tableName">
          <el-input v-model="form.createTime" placeholder="请输入关联表名称" />
        </el-form-item>
        <el-form-item label="状态" prop="tableId">
          <el-input v-model="form.state" placeholder="请输入关联表ID" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 查看日志 -->
    <el-dialog title="查看日志" :visible.sync="logVisible" width="800px" append-to-body >
      <el-table :data="logData">
        <el-table-column property="createTime" label="申请时间" width="150"></el-table-column>
        <el-table-column property="personnelName" label="操作人姓名" width="200"></el-table-column>
        <el-table-column property="state" label="申请状态" width="200" :formatter="stateFormat"></el-table-column>
        <el-table-column property="content" label="备注" width="200"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="logVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
    
    <!-- 上传文件 -->
     <el-dialog :title="upload.title" :visible.sync="upload.open" :close-on-click-modal="false"  width="800px" append-to-body>
      <el-tabs v-model="upload.activeName">
        <el-tab-pane id="fileUpload" label="上传" name="first" v-hasPermi="['myjob:waitwork:uploadFile']">
              <el-upload ref="upload" 
              :headers="upload.headers" 
              :limit="1" 
              :data="upload.data"
              :action="upload.url" 
              :disabled="upload.isUploading" 
              :on-progress="handleFileUploadFile" 
              :on-success="handleFileSuccess" 
              :auto-upload="false" drag>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或
                <em>点击上传</em>
              </div>
            </el-upload>
          <el-button type="primary" @click="submitFileForm" style="display:block;margin:0 auto;marginTop:1em">上 传</el-button>
        </el-tab-pane>
        <el-tab-pane label="附件查看" name="second">
            <el-row :gutter="10" class="mb8">
            </el-row>
            <el-table v-loading="loading" :data="upload.fileLists" border @selection-change="handleSelectionFileChange">
                  <el-table-column type="selection" width="55" align="center" />
                  <el-table-column label="文件ID" align="center" prop="id" v-if="false"/>
                  <el-table-column label="文件URL" align="center" prop="url" v-if="false"/>
                  <el-table-column label="文件名称" align="center" prop="name"/>
                  <el-table-column label="文件类型" align="center" prop="type" :formatter="stateFileTypeFormat" />
                  <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        v-hasPermi="['myjob:waitwork:downFile']"
                        @click="handleFileDownload(scope.row)"
                      >下载</el-button>
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleFileDelete(scope.row)"
                        v-hasPermi="['myjob:waitwork:deleFile']"
                      >删除</el-button>
                    </template>
                  </el-table-column>
            </el-table>
            <pagination
              v-show="upload.total>0"
              :total="upload.total"
              :page.sync="upload.queryParams.pageNum"
              :limit.sync="upload.queryParams.pageSize"
              @pagination="getList"
            />
        </el-tab-pane>
        <el-tab-pane label="相关附件" name="third">
            <el-row :gutter="10" class="mb8">
              <el-table v-loading="loading" :data="upload.relevantFile" border @selection-change="handleSelectionFileChange">
                  <el-table-column type="selection" width="55" align="center" />
                  <el-table-column label="文件ID" align="center" prop="id" v-if="false"/>
                  <el-table-column label="文件URL" align="center" prop="url" v-if="false"/>
                  <el-table-column label="文件名称" align="center" prop="name"/>
                  <el-table-column label="文件类型" align="center" prop="type" :formatter="stateFileTypeFormat" />
                  <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        v-hasPermi="['myjob:waitwork:downFile']"
                        @click="handleFileDownload(scope.row)"
                      >下载</el-button>
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleFileDelete(scope.row)"
                        v-hasPermi="['myjob:waitwork:deleFile']"
                      >删除</el-button>
                    </template>
                  </el-table-column>
            </el-table>
            </el-row>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitFileForm">确 定</el-button> -->
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { submitCheck} from "@/api/myjob/waitwork/waitWork.js";
import { listApply, getApply, delApply, addApply, updateApply, exportApply, logList, FileAllList, flowList, ReFlowData } from "@/api/workflow/apply";
import { selectFiles,deleteFiles } from "@/api/work/user";
import {getToken } from "@/utils/auth";
import {getUserTree} from "@/api/trialproduce/car";
import Editor from '@/components/Editor';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";


export default {
  name: "Apply",
  components: { 
    Treeselect,
    Editor 
  },
  data() {
    return {
      // 审核状态字典
      stateOptions: [],
      // 遮罩层
      loading: true,
      flowData:{},
      checkId: '',
      state:'',
      applyId: '',
      // 流程模态框
      flowVisible: false,
      title: '',
      flowForm: {},
      applyType: '',
      // 日志
      logData: [],
      logVisible: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工作申请表格数据
      applyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 申请类型字典
      applyTypeOptions: [],
      //用户数结构
      userTree:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        applyUserId: null,
        applyType: null,
      },
      // 表单参数
      form: {},
      upload: {
        title: null,
        open: false,
        // 上传标签页
        activeName: 'first',
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken()},
        // 是否禁用上传
        isUploading: false,
        // 上传的地址
        url: process.env.VUE_APP_BASE_API+"/work/process/user/upload",
        //路径
        baseURL:  process.env.VUE_APP_BASE_API,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken()},
        data: {
          tableId: null
        },
        //总数
        total: 0,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        relevantFile: [{
          id:'',
          url: "",
          name: '',
          type: ''
        }],
        fileLists: [{
          id:'',
          url: "",
          name: '',
          type: ''
        }],
      },
      //文件类型
      textFileTypeOptions: [],
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.handleUserTree();
    this.getDicts("wf_apply_type").then(response => {
      this.applyTypeOptions = response.data;
      console.log(this.applyTypeOptions)
    });
    this.getDicts("wf_check_state").then(response => {
      this.stateOptions = response.data;
    });
    this.getDicts("sys_file_type").then(response => {
      this.textFileTypeOptions = response.data;
    });
  },
  methods: {
    // 文件类型翻译
    stateFileTypeFormat(row, column) {
      return this.selectDictLabel(this.textFileTypeOptions, row.type);
    },
    // 审核状态字典翻译
    stateFormat(row, column) {
      return this.selectDictLabel(this.stateOptions, row.state);
    },
    // 查看日志
    handleLog(row){
      var applyId = row.applyId
      var query ={
         applyId: applyId
      }
      this.logVisible = true
      logList(query).then(response => {
        console.log('查看日志', response)
        this.logData = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 一个人提交审核
    handleCheckOnePerson(row){
      // let isSubmitFile = row.isSubmitFile;
      var tableId = row.tableId
      var applyId = row.applyId
      var data = {
        applyId
      }
      this.$confirm('是否提交编号为"' + tableId + '"的数据?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return ReFlowData(data);
        }).then(() => {
          this.getList();
          this.msgSuccess("提交审核成功");
        }).catch(function() {});
      // if(isSubmitFile=="Y"){
      //   selectFiles(this.upload.data.tableId).then((response) => {
      //       if(response.total<=0){
      //         this.$message({
      //           showClose: true,
      //           message: '请上传附件后提交审核！',
      //           type: 'warning'
      //         });
      //       }
      //     });
      //  }else{
      //   this.$confirm('是否提交编号为"' + tableId + '"的数据?', "警告", {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     type: "warning"
      //   }).then(function() {
      //     return ReFlowData(applyId);
      //   }).then(() => {
      //     this.getFileList();
      //     this.msgSuccess("提交审核成功");
      //   }).catch(function() {});
      //  }
      
    },
    /** 附件上传按钮操作 */
    handleFileUpload(row) {
      const itemId = row.tableId;
      this.upload.title = "上传附件";
      this.upload.open = true;
      this.upload.data.tableId = itemId;
      this.getFileList();
    },
    // 附件上传中处理
    handleFileUploadFile(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 附件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = true;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "上传结果", { dangerouslyUseHTMLString: true });
      this.getFileList();
      this.getList();
    },
    // 附件提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
     //附件列表
    handleSelectionFileChange(selection){
      this.id = selection.map(item => item.id)
      this.uri = selection.map(item => item.uri)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 查询附件列表 */
    getFileList() {
      this.loading = true;
      console.log('附件列表', this.upload.data.tableId)

      FileAllList(this.upload.data.tableId).then((response) => {
        console.log('附件列表', response)
        this.upload.fileLists = response.data.itemFile;
        this.upload.relevantFile = response.data.relevantFile;
        // this.upload.total = response.total;
        this.loading = false;
      });
    },
    // 删除文件操作
    handleFileDelete(row){
      const id = row.id || this.id;
      this.$confirm('是否确认删除任务分配编号为"' + id + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return deleteFiles(id);
        }).then(() => {
          this.getFileList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    // 下载文件
    handleFileDownload(row){
      const id = row.id || this.id;
      const url = row.uri || this.uri;
      window.location.href = this.baseURL+url;
    },
    //用户树
    handleUserTree(){
      getUserTree().then(response => {
        this.userTree = response.data;
      });
    },
    /** 查询工作申请列表 */
    getList() {
      this.loading = true;
      listApply(this.queryParams).then(response => {
        this.applyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 申请类型字典翻译
    applyTypeFormat(row, column) {
      return this.selectDictLabel(this.applyTypeOptions, row.applyType);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        applyId: null,
        applyUserId: null,
        applyType: null,
        applyContent: null,
        tableName: null,
        tableId: null,
        createTime: null,
        updateTime: null,
        remark: null,
        checkUserId: null
      };
      
      this.resetForm("form");
      this.flowForm = {
        content: null
      }
      this.resetForm("flowForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.applyId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加工作申请";
    },
    /** 提交审核 */
    handleCheck(row) {
       const itemId = row.tableId;
       let isSubmitFile = row.isSubmitFile;
       this.upload.data.tableId = itemId;
       if(isSubmitFile=="Y"){
        selectFiles(this.upload.data.tableId).then((response) => {
            if(response.total<=0){
              this.$message({
                showClose: true,
                message: '请上传附件后提交审核！',
                type: 'warning'
              });
            }else{
              this.openCheckView(row);
            }
          });
       }else{
           this.openCheckView(row);
       }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const applyId = row.applyId || this.ids
      getApply(applyId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改工作申请";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.applyId != null) {
            updateApply(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addApply(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const applyIds = row.applyId || this.ids;
      this.$confirm('是否确认删除工作申请编号为"' + applyIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delApply(applyIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有工作申请数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportApply(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    
  }
};
</script>
<style >
.el-upload-list__item-name{
    font-size: 16px;
}
#fileUpload .el-upload-dragger{
  display:block;
  margin:0 auto;
  margin-top:1em;
  width: 760px;
  height: 180px;
}
</style>
